<template>
  <div
    :style="{
      padding: '24px',
      background: '#fff',
      postion: 'absolute',
      height: '90%',
    }"
  >
    <a-space direction="vertical" size="Large">
      <div>
        <a-form-model layout="inline" :model="formInline">
          <a-form-model-item label="年级:">
            <a-input
              v-model="formInline.grade"
              placeholder="根据年级查询"
              style="width: 280px"
            >
            </a-input>
          </a-form-model-item>
          <a-form-model-item label="班级:">
            <a-input
              v-model="formInline.name"
              placeholder="根据班级查询"
              style="width: 280px"
            >
            </a-input>
          </a-form-model-item>
          <a-form-model-item>
            <a-button type="primary" @click="find"> 查询 </a-button>
          </a-form-model-item>
          <a-form-model-item>
            <a-button @click="resetForm()">重置</a-button>
          </a-form-model-item>
          <a-form-model-item>
            <a-button type="link" v-show="showSrech" @click="changShow()">
              展开 <a-icon type="down"
            /></a-button>
            <a-button type="link" v-show="!showSrech" @click="changShow()">
              收起 <a-icon type="up"
            /></a-button>
          </a-form-model-item>
          <a-form-model-item label="班主任:" v-show="!showSrech">
            <a-input
              v-model="formInline.headmaster"
              placeholder="根据班主任查询"
              style="width: 280px"
            >
            </a-input>
          </a-form-model-item>
          <a-form-model-item label="班级助理:" v-show="!showSrech">
            <a-input
              v-model="formInline.assistant"
              placeholder="根据班级助理查询"
              style="width: 280px"
            >
            </a-input>
          </a-form-model-item>
        </a-form-model>
      </div>
      <div style="width: 100%; margin-top: 10px">
        <a-alert :message="'已选择: ' + this.selectNum" type="info" show-icon />
      </div>

      <div style="float: left">
        <a-button type="primary" @click="showModal(0)">
          <a-icon type="plus" />
          新建
        </a-button>
        <a-button
          type="danger"
          v-show="selectNum > 0"
          style="margin-left: 10px"
          @click="delClass"
        >
          删除
        </a-button>
        <a-modal
          :title="title"
          :visible="visible"
          :confirm-loading="confirmLoading"
          @ok="handleOk(0)"
          @cancel="handleCancel"
        >
          <a-form-model
            ref="ruleForm"
            :model="ruleForm"
            :rules="addRules"
            v-bind="layout"
          >
            <a-form-model-item has-feedback label="年级" prop="grade">
              <a-input
                v-model="ruleForm.grade"
                autocomplete="off"
                placeholder="请输入年级(实例：2)"
                valu
              >
              </a-input>
            </a-form-model-item>
            <a-form-model-item has-feedback label="班级" prop="name">
              <a-input
                v-model="ruleForm.name"
                autocomplete="off"
                allow-clear
                placeholder="请输入班级(实例：2)"
              >
              </a-input>
            </a-form-model-item>
            <a-form-model-item has-feedback label="班主任" prop="headmaster">
              <a-select
                v-model="ruleForm.headmaster"
                placeholder="请选择班主任"
                style="width: 180px"
              >
                <a-select-option
                  v-for="(item, index) in headmasterlist"
                  :key="index"
                  :value="item.tno"
                >
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
            <a-form-model-item has-feedback label="班级助理" prop="assistant">
              <a-select
                v-model="ruleForm.assistant"
                placeholder="请选择班级助理"
                style="width: 180px"
              >
                <a-select-option
                  v-for="(item, index) in assistantlist"
                  :key="index"
                  :value="item.tno"
                >
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-form-model>
        </a-modal>
      </div>

      <div>
        <a-table
          :columns="columns"
          :data-source="data"
          :row-selection="rowSelection"
          @change="onChange"
          :loading="spin"
        >
          <span slot="name" slot-scope="text">{{ text }} 班</span>
          <template slot="action" slot-scope="text, record">
            <a-button
              type="link"
              slot="action"
              style="padding-left: 0%; padding-right: 0%"
              @click="showModal(record)"
            >
              编辑
            </a-button>
          </template>
        </a-table>
      </div>
    </a-space>
  </div>
</template>

<script>
const columns = [
  {
    title: "#",
    dataIndex: "id",
    key: "id",
    // id自增
    customRender: function (text, record, index) {
      return index + 1;
    },
  },
  {
    title: "年级",
    dataIndex: "grade",
    key: "grade",
  },
  {
    title: "班级",
    dataIndex: "name",
    key: "name",
    scopedSlots: { customRender: "name" },
  },
  {
    title: "班主任",
    dataIndex: "headmaster",
    key: "headmaster",
    scopedSlots: { customRender: "headmaster" },
  },
  {
    title: "班级助理",
    dataIndex: "assistant",
    key: "assistant",
    scopedSlots: { customRender: "assistant" },
  },
  {
    title: "操作",
    dataIndex: "action",
    key: "action",
    ellipsis: true,
    scopedSlots: { customRender: "action" },
  },
];

import {
  getClassManage,
  delClass,
  teacherNull,
  addClass,
  editClass,
} from "@/utils/api";
export default {
  name: "ClassManage",
  components: {},
  data() {
    let validateName = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("班级不能为空！"));
      } else if (!/^[1-9]{1}[0-9]{0,1}$/.test(value)) {
        callback(new Error("该项只能为数字,且在1-99之间"));
      } else {
        callback();
      }
    };
    let validateGrade = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("年级不能为空！"));
      } else if (!/^[1-6]{1}$/.test(value)) {
        callback(new Error("该项只能为数字，且在1-6之间"));
      } else {
        callback();
      }
    };
    return {
      formInline: {
        name: "",
        grade: "",
        headmaster: "",
        assistant: "",
      },
      ruleForm: {
        id: "",
        name: "",
        grade: "",
        headmaster: "",
        assistant: "",
      },
      addRules: {
        grade: [{ validator: validateGrade, trigger: "change" }],
        headmaster: [
          { required: true, message: "班主任不能为空!", trigger: "change" },
        ],
        assistant: [
          { required: true, message: "班级助理不能为空!", trigger: "change" },
        ],
        name: [{ validator: validateName, trigger: "change" }],
      },
      layout: {
        labelCol: { span: 5 },
        wrapperCol: { span: 15 },
      },
      data: [],
      headmasterlist: [],
      assistantlist: [],
      columns,
      selectNum: 0,
      selectedRowKeys: [],
      visible: false,
      confirmLoading: false,
      showSrech: true,
      curriculumName: [],
      selectedRow: [],
      editKey: "",
      spin: false,
    };
  },
  created() {
    this.getTeacherNull();
    // 获取班级信息
    this.find();
  },
  computed: {
    rowSelection() {
      const { selectedRowKeys } = this; // selectedRowKeys和取消选中有关，我也看不懂
      return {
        selectedRowKeys,
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectedRowKeys = selectedRowKeys;
          this.selectNum = selectedRows.length;
          // 获取选中的数据
          this.selectedRow = selectedRows;
        },
      };
    },
  },
  // 去掉表单验证信息二次打开残留
  watch: {
    // 去掉表单验证信息二次打开残留
    visible(val) {
      //监听的是控制模态框显示或影藏开关的布尔值
      // 监视dialog状态（打开、关闭）
      if (val) {
        try {
          this.$nextTick(() => {
            this.$refs["ruleForm"].clearValidate() ; // 重置编辑表单
          });

          // addForm 为ref指向的表单
        } catch (e) {
          console.log(e);
        }
      }
    },
  },
  methods: {
    onChange() {
      this.selectNum = 0;
      this.selectedRowKeys = []; //取消可选
    },
    // 改变展开状态
    changShow() {
      this.showSrech = !this.showSrech;
    },
    // 查询表单查询
    find() {
      this.spin = true;
      getClassManage(this.formInline).then((res) => {
        this.spin = false;
        this.$nextTick(() => {
          this.data = res.data;
        });
      });
    },
    // 查询表单重置
    resetForm() {
      this.formInline = {};
      this.$$nextTick(() => {
        this.$refs.ruleForm.clearValidate();
      });
    },
    // 获取教师方法
    getTeacherNull() {
      const params1 = new URLSearchParams();
      const params2 = new URLSearchParams();
      //获取没当班主任的教师
      params1.append("teacher", "headmaster");
      teacherNull(params1).then((res) => {
        this.headmasterlist = res.data;
      });
      // 获取没当班级助理的教师
      params2.append("teacher", "assistant");
      teacherNull(params2).then((res) => {
        this.assistantlist = res.data;
      });
    },
    // 显示关闭弹窗
    showModal(record) {
      if (record != 0) {
        this.title = "修改班级信息";
        let edit = JSON.parse(JSON.stringify(record));
        this.editKey = edit.key;
        this.ruleForm.id = edit.id;
        this.ruleForm.name = edit.name;
        this.ruleForm.grade = edit.grade;
        this.ruleForm.headmaster = edit.teacher1.name;
        this.ruleForm.assistant = edit.teacher2.name;
        console.log(edit);
        this.visible = true;
      } else {
        this.title = "新建班级";
        this.visible = true;
      }
    },
    // 新建/配置 弹窗 确认 按钮
    handleOk() {
      if (this.editKey != "") {
        // 编辑确认
        this.$refs["ruleForm"].validate((valid) => {
          if (valid) {
            this.visible = false;
            editClass(this.ruleForm).then((res) => {
              this.$nextTick(() => {
                if (res.data != null) this.data = res.data;
              })
            });
          }
        });
      } else {
        // 新建确认
        this.$refs["ruleForm"].validate((valid) => {
          if (valid) {
            this.visible = false;
            addClass(this.ruleForm).then((res) => {
              if (res.data != null) this.data = res.data;
              this.getTeacherNull();
            });
          }
        });
      }
      this.ruleForm = {};
    },
    // 新建弹窗 取消 按钮
    handleCancel() {
      this.ruleForm = {};
      this.visible = false;
    },
    // 删除班级
    delClass() {
      let ids = [];
      this.selectedRow.forEach((element) => {
        ids.push(element.id);
      });
      delClass(ids).then((res) => {
        if (res.data != null) {
          this.data = res.data;
        }
      });
    },
  },
};
</script>
<style>
</style>